import time
import pymysql
from selenium import webdriver

conn = pymysql.connect(user='root', password='123456', host='localhost', port=3306, database='web')
cursor = conn.cursor()
cursor.execute('drop table if exists qqemail;')
cursor.execute("""CREATE TABLE qqemail (
            title varchar(255),
            sender varchar(255),
            time varchar(255),
            content longtext);""")
# # 自动登陆
browser =webdriver.Firefox(executable_path ="C:\Program Files\Mozilla Firefox\geckodriver.exe")
browser.get('https://mail.qq.com/')
browser.switch_to.frame('login_frame')
# 账号输入
accountInput = browser.find_element_by_id('u')
accountInput.clear()
accountInput.send_keys('···QQ邮箱····')
# 密码输入
passwordInput = browser.find_element_by_id('p')
passwordInput.send_keys('····QQ密码····')
# 点击按钮
loginButton = browser.find_element_by_id('login_button')
loginButton.click()
time.sleep(15)
browser.switch_to.default_content()
browser.find_element_by_id('folder_1').click()
# 　爬取邮件
browser.switch_to.frame('mainFrame')
browser.find_element_by_xpath("//td[contains(@class, 'tl tf')]").click()
while True:
    try:
        email = (
            browser.find_element_by_id('subject').text,
            browser.find_element_by_id('tipFromAddr_readmail').text,
            browser.find_element_by_id('local-time-caption').text,
            browser.find_element_by_id('mailContentContainer').text
        )
        print(email)
        cursor.execute("INSERT IGNORE INTO qqemail ('{title}','{sender}','{time}','{content}');".format(title=email[0],sender=email[1],time=email[2],content=email[3]))
    except Exception as e:
        print(e)
    try:
        nextA = browser.find_element_by_xpath('//a[@id="nextmail" and  @ck="prevandnext"]')

        # 防止弹出请求频率过快
        time.sleep(5)
        nextA.click()
    except Exception as e:
        print(e)
        browser.close()
        browser.quit()
        break

conn.commit()

